package com.cblz.bd.server.frontend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cblz.bd.common.core.constant.RedisConstant;
import com.cblz.bd.common.core.exception.BdAdminException;
import com.cblz.bd.redis.spring.boot.starter.service.RedisService;
import com.cblz.bd.server.frontend.entity.BaUserGroup;
import com.cblz.bd.server.frontend.mapper.BaUserGroupMapper;
import com.cblz.bd.server.frontend.service.BaUserGroupService;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author yanjieping
 * @description 针对表【ba_user_group(会员组表)】的数据库操作Service实现
 * @createDate 2022-11-04 15:09:54
 */
@Service("baUserGroupService")
@RequiredArgsConstructor
public class BaUserGroupServiceImpl extends ServiceImpl<BaUserGroupMapper, BaUserGroup> implements BaUserGroupService {

    private final RedisService redisService;

    /**
     * 根据用户ID拿到对应的权限信息
     *
     * @param userGroupId 用户ID
     * @return 权限ID集合
     */
    @Override
    public Tuple2<BaUserGroup, List<String>> getRulesByUserId(Integer userGroupId) {
        String key = RedisConstant.USER_RULE_GROUP_CACHE_PREFIX.getValue() + userGroupId;

        BaUserGroup baUserGroup = (BaUserGroup) redisService.get(key);
        if (Objects.isNull(baUserGroup)) {
            baUserGroup = Option.of(getById(userGroupId)).getOrElseThrow(() -> {
                redisService.set(key + "--null", "null", 60 * 2L);
                throw new BdAdminException("未找到ID为「" + userGroupId + "」的用户组");
            });
            redisService.set(key, baUserGroup, 60 * 10L);
        }

        List<String> rulesList = Arrays.stream(baUserGroup.getRules().split(",")).toList();

        return Tuple.of(baUserGroup, rulesList);
    }
}




